<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t(title)" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'650px':'680px'" top='10px' @close='close'>
    <div class="dialogContentBox">
      <el-form ref="form" :model="record" label-width="120px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('名称')" prop="name">
          <el-input v-emoji v-model="record.name" style="width:217px;" size='small' ref="commodityName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('IP类型')" prop="iptype">
          <el-radio v-model="record.iptype" :disabled="title === '编辑'" label="ipv4" class="IPv4">IPv4</el-radio>
          <el-radio v-model="record.iptype" :disabled="title === '编辑'" label="ipv6" class="IPv6">IPv6</el-radio>
        </el-form-item>
        <el-form-item :label="$t('动作')" prop="action">
          <el-select v-model="record.action" ref="policyType" :disabled="title === '编辑'" size='small'>
            <el-option v-for="(item,index) in actionList" :id="`strategy-action${index}`" :key="item.value" :label="$t('eventaction.' + item.label)" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('入侵防御策略名称')" v-if="record.action === 'se'" prop="ips">
          <el-select v-model="record.ips" :placeholder="$t('请选择')" ref="ips" size='small' filterable clearable>
            <el-option v-for="(item,index) in ipsList" :id="`strategy-ips${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('病毒过滤策略名称')" v-if="record.action === 'se'" prop="av">
          <el-select v-model="record.av" :placeholder="$t('请选择')" ref="av" size='small' filterable clearable>
            <el-option v-for="(item,index) in avList" :id="`strategy-av${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('URL策略名称')" v-if="record.action === 'se'" prop="url-filter">
          <el-select v-model="record['url-filter']" :placeholder="$t('请选择')" ref="filter" size='small' filterable clearable>
            <el-option v-for="(item,index) in urlFilterList" :id="`strategy-url-filter${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('深度过滤策略名称')" v-if="record.action === 'se'" prop="content-filter">
          <el-select v-model="record['content-filter']" :placeholder="$t('请选择')" ref="content" size='small' filterable clearable>
            <el-option v-for="(item,index) in contentFilterList" :id="`strategy-content-filter${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('源区域')" prop="szone">
          <el-select v-model="record.szone" ref="szone" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in szoneList" :id="`strategy-szone${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <szone-dialog @szoneList='safeList' :nameType='"szone"' id="strateg-dialogs-zone"></szone-dialog>
        </el-form-item>
        <el-form-item :label="$t('目的区域')" prop="dzone">
          <el-select v-model="record.dzone" ref="dzone" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in dzoneList" :id="`strategy-dzone${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <szone-dialog @szoneList='safeList' :nameType='"dzone"' id="strateg-dialogs-dzone"></szone-dialog>
        </el-form-item>
        <el-form-item :label="$t('源IP')" prop="sip">
          <el-select v-model="record.sip" ref="srcIp" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in filMac(sipList)" :id="`strategy-srcIp${index}`" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"sip"' id="strateg-dialogs-sip"></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('目的IP')" prop="dip">
          <el-select v-model="record.dip" ref="dstIp" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in filMac(dipList)" :id="`strategy-dstIp${index}`" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"dip"' id="strateg-dialogs-dip"></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('源MAC')" prop="smac">
          <el-select v-model="record.smac" ref="smac" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in smacList" :id="`strategy-smac${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <MacDialog @commandList='commandMacList' :nameType='"smac"' id="strateg-dialogs-smac"></MacDialog>
        </el-form-item>
        <el-form-item :label="$t('目的MAC')" prop="dmac">
          <el-select v-model="record.dmac" ref="dmac" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in smacList" :id="`strategy-dmac${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <MacDialog @commandList='commandMacList' :nameType='"dmac"' id="strateg-dialogs-dmac"></MacDialog>
        </el-form-item>
        <el-form-item :label="$t('用户')" prop="user">
          <el-select v-model="record.user" ref="user" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in userList" :id="`strategy-user${index}`" :key="item.name" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" plain size='small' style="margin-left:10px" @click="userDialogVisible" class="userDialogVisible">{{$t('新建用户')}}</el-button>
          <el-button type="primary" plain size='small' @click="groupDialogVisible" class="groupDialogVisible">{{$t('新建用户组')}}</el-button>
          <group-dialog v-if="groupDialog" ref="refGroupDialogVisible" @userListData='userListData'></group-dialog>
          <user-dialog v-if="userDialog" ref="refUserDialogVisible" @userListData='userListData'></user-dialog>
        </el-form-item>
        <el-form-item :label="$t('协议')" prop="proto">
          <el-select v-model="record.proto" ref="proto" :placeholder="$t('请选择')" @change="protoChange" size='small'>
            <el-option v-for="(item,index) in protoList" :id="`strategy-proto${index}`" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('源端口')" prop="sport">
          <el-tooltip :content="$t('配置源端口需要先配置协议')" placement="bottom" effect="light" :disabled='record.proto !== "nothing"'>
            <el-input v-emoji v-model="record.sport" ref="sport" style="width:217px;" :disabled='record.proto === "nothing"' size='small'></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item :label="$t('服务')" prop="service">
          <el-select v-model="record.service" ref="service" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in serviceList" :id="`strategy-service${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <ServerDialog @serviceList='serviceAddList'></ServerDialog>
        </el-form-item>
        <el-form-item :label="$t('应用')" prop="app">
          <el-select v-model="record.app" :placeholder="$t('请选择')" ref="app" size='small' filterable clearable>
            <el-option v-for="(item,index) in appList" :id="`strategy-app${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <AppDialog @appDataList='appDataList' :policyType='policyType'></AppDialog>
        </el-form-item>
        <el-form-item :label="$t('时间')" prop="time">
          <el-select v-model="record.time" ref="time" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="(item,index) in timeList" :id="`strategy-time${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <TimeDialog @timeDataList='timeDataList'></TimeDialog>
        </el-form-item>
        <el-form-item :label="$t('策略使能')" prop="enable">
          <el-switch :width="45" v-model="record.enable" active-color="#009966" class="enable switch" inactive-color="#CCCCCC" active-value="yes" inactive-value="no" :active-text="$t('开')" :inactive-text="$t('关')"></el-switch>
        </el-form-item>
        <el-form-item :label="$t('日志使能')" prop="log">
          <el-switch :width="45" v-model="record.log" class="logEnable switch" active-color="#009966" inactive-color="#CCCCCC" active-value="on" inactive-value="off" :active-text="$t('开')" :inactive-text="$t('关')"></el-switch>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addClick">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="delClick">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addPolicy, editPolicy } from '@/api/safe/access/strategy'
import { getSafeArray } from '@/api/list/safe'
import { getAddrGroupArray } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { getServiceArray, getServiceReArray } from '@/api/list/server'
import { getTimeArray } from '@/api/list/time'
import { getAppArray, getAppReArray } from '@/api/list/app'
import { getGroupUserInfo, getUserArray } from '@/api/user/user'
import { getWhiteList } from '@/api/safe/white'
import { getBlacklist, getBlacklistFile } from '@/api/safe/black'
import { getAssetArray } from '@/api/list/assets/assetobject'
import { getAssetGroupArray } from '@/api/list/assets/assetGroup'
import { getIpsArray } from '@/api/safe/ips'
import { getAvArray } from '@/api/safe/av'
import { getUrlArray } from '@/api/safe/url'

import szoneDialog from './SzoneDialog'
import addrDialog from './AddrDialog'
import ServerDialog from './ServerDialog'
import TimeDialog from './TimeDialog'
import AppDialog from './AppDialog'
import MacDialog from './MacDialog'
import GroupDialog from './userTools/GroupDialog'
import UserDialog from './userTools/UserDialog'
import { inputClass, selectClass } from '@/utils/input-class.js'

export default {
  name: 'StrategyDialog',
  props: {
    policyTypeInner: {
      type: String,
      required: 'whitelist'
    }
  },
  components: {
    szoneDialog,
    addrDialog,
    ServerDialog,
    TimeDialog,
    AppDialog,
    GroupDialog,
    UserDialog,
    MacDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('请输入名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      userDialog: false,
      groupDialog: false,
      lang: this.$i18n.locale,
      record: {
        id: null,
        name: '',
        iptype: 'ipv4',
        action: 'DROP',
        szone: '',
        dzone: '',
        sip: '',
        dip: '',
        smac: '',
        dmac: '',
        user: '',
        proto: 'nothing', // nothing
        sport: '',
        service: '',
        app: '',
        time: '',
        enable: 'yes', // yes/空
        log: 'off', // on/off
        ips: '',
        av: '',
        'url-filter': '',
        'content-filter': ''
      },
      recordCopy: {
        id: null,
        name: '',
        iptype: 'ipv4',
        action: 'DROP',
        szone: '',
        dzone: '',
        sip: '',
        dip: '',
        smac: '',
        dmac: '',
        user: '',
        proto: 'nothing',
        sport: '',
        service: '',
        app: '',
        time: '',
        enable: 'yes', // yes/空
        log: 'off', // on/off
        ips: '',
        av: '',
        'url-filter': '',
        'content-filter': ''
      },
      policyType: '',
      title: '',
      actionList: [
        { label: '允许', value: 'ACCEPT' },
        { label: '丢弃', value: 'DROP' },
        { label: '拒绝', value: 'REJECT' },
        { label: '安全引擎', value: 'se' }],
      ipsList: [],
      avList: [],
      urlFilterList: [],
      contentFilterList: [],
      szoneList: [],
      dzoneList: [],
      sipList: [],
      dipList: [],
      smacList: [],
      userList: [],
      protoList: [
        { value: 'nothing', label: this.$t('未配置') },
        { value: 'tcp', label: 'tcp' },
        { value: 'udp', label: 'udp' },
        { value: 'dccp', label: 'dccp' },
        { value: 'sctp', label: 'sctp' }
      ],
      serviceList: [],
      appList: [],
      timeList: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.action' (val) {
      if (val === 'se') {
        this.$nextTick(() => {
          const selectData = ['ips', 'av', 'filter', 'content']
          selectClass(this.$refs, selectData)
        })
      }
    }
  },
  methods: {
    filMac(list=[]) {
      return list.filter(item => item.ip_type !== 7)
    },
    init (data, policyType) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['sport', 'commodityName']
        const selectData = ['policyType', 'szone', 'dzone', 'srcIp', 'dstIp', 'smac', 'dmac', 'user', 'proto', 'service', 'app', 'time']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      this.policyType = policyType
      if (policyType === 'whitelist') {
        this.record.action = 'ACCEPT'
      }
      this.title = data ? '编辑' : '添加'
      if (data) {
        this.record = Object.assign(this.record, data)
        if (data.index) {
          this.record.id = data.index
        }
      }
      this.safeList()
      this.commandList()
      this.serviceAddList()
      this.timeDataList()
      this.appDataList()
      this.userListData()
      this.contentFilterListData()
    },
    submit () {
      if (!this.record.id) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            addPolicy(this.record).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('添加成功'))
                this.close()
                this.$parent.listData()
              }
              if (res.info && res.info[0] && res.info[0].reload === 'yes') {
                this.$parent.openTip()
              }
            })
          }
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            editPolicy(this.record).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('编辑成功'))
                this.close()
                this.$parent.listData()
              }
              if (res.info && res.info[0] && res.info[0].reload === 'yes') {
                this.$parent.openTip()
              }
            })
          }
        })
      }
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.ipsList = []
      this.avList = []
      this.urlFilterList = []
      this.contentFilterList = []
      this.szoneList = []
      this.dzoneList = []
      this.sipList = []
      this.dipList = []
      this.smacList = []
      this.userList = []
      this.serviceList = []
      this.appList = []
      this.timeList = []
      this.$refs.form.resetFields()
    },
    userDialogVisible () {
      this.userDialog = true
      this.$nextTick(() => {
        this.$refs.refUserDialogVisible.init()
      })
    },
    groupDialogVisible () {
      this.groupDialog = true
      this.$nextTick(() => {
        this.$refs.refGroupDialogVisible.init()
      })
    },
    safeList (data, nameType) {
      this.szoneList = []
      this.dzoneList = []
      getSafeArray().then(response => {
        if (response.status === 0) {
          this.szoneList = response.info
          this.dzoneList = response.info
        }
      })
      if (data && nameType === 'szone') {
        this.record.szone = data.name
      } else if (data && nameType === 'dzone') {
        this.record.dzone = data.name
      }
    },
    commandMacList (data, nameType, name) {
      this.smacList = []
      getAddrArray().then(response => {
        if (response.status === 0) {
          for (let item of response.info) {
            if (item.ip_type === 7) {
              this.smacList.push(item)
            }
          }
        }
      })
      this.record[nameType] = name
    },
    commandList (data, nameType, name) {
      this.sipList = []
      this.dipList = []
      this.smacList = []
      getAddrArray().then(response => {
        if (response.status === 0) {
          for (let item of response.info) {
            if (item.ip_type === 7) {
              this.smacList.push(item)
            }
          }
          getAddrGroupArray().then(res => {
            if (res.status === 0) {
              getAssetArray().then(resAsset => {
                if (resAsset.status === 0) {
                  getAssetGroupArray().then(resAssetGroup => {
                    if (resAssetGroup.status === 0) {
                      for (let item of response.info) {
                        item.nameShow = this.$t('地址-') + item.name
                        this.sipList.push(item)
                        this.dipList.push(item)
                      }
                      for (let item of res.info) {
                        item.nameShow = this.$t('地址组-') + item.name
                        this.sipList.push(item)
                        this.dipList.push(item)
                      }
                      for (let item of resAsset.info) {
                        item.nameShow = this.$t('资产对象-') + item.name
                        this.sipList.push(item)
                        this.dipList.push(item)
                      }
                      for (let item of resAssetGroup.info) {
                        item.nameShow = this.$t('资产组-') + item.name
                        this.sipList.push(item)
                        this.dipList.push(item)
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
      if (data && nameType === 'sip') {
        this.record.sip = name
      } else if (data && nameType === 'dip') {
        this.record.dip = name
      }
    },
    serviceAddList (data) {
      this.serviceList = []
      getServiceArray().then(response => {
        if (response.status === 0) {
          getServiceReArray().then(res => {
            if (res.status === 0) {
              this.serviceList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.service = data.name
      }
    },
    timeDataList (data) {
      this.timeList = []
      getTimeArray().then(response => {
        if (response.status === 0) {
          this.timeList = response.info
        }
      })
      if (data) {
        this.record.time = data.name
      }
    },
    appDataList (data, appType) {
      this.appList = []
      getAppArray().then(response => {
        if (response.status === 0) {
          getAppReArray().then(res => {
            if (res.status === 0) {
              let appList = response.info.concat(res.info)
              // 过滤
              this.appList = appList.filter(v => this.policyTypeInner.indexOf(v.app_type) > -1 || v.app_type === 'any')
            }
          })
        }
      })
      // white/black/any
      if (data && (appType === 'white' || appType === 'any') && this.policyTypeInner === 'whitelist') {
        this.record.app = data.name
      } else if (data && this.policyTypeInner !== 'whitelist') {
        this.record.app = data.name
      }
    },
    userListData (name) {
      getGroupUserInfo({ name: 'root' }).then(res => {
        if (res.status === 0) {
          getUserArray().then(response => {
            if (response.status === 0) {
              let groupList = []
              let groupListGroup = []
              for (let item of res.info) {
                item.nameShow = this.$t('用户-') + item.name
                groupList.push(item)
              }
              for (let item of response.info) {
                item.nameShow = this.$t('用户组-') + item.name
                groupListGroup.push(item)
              }
              groupListGroup.splice(0, 1)
              this.userList = groupList.concat(groupListGroup)
              if (name) {
                this.record.user = name
              }
            }
          })
        }
      })
    },
    contentFilterListData () {
      getIpsArray().then(res => {
        if (res.status === 0) {
          this.ipsList = res.info
        }
      })
      getAvArray().then(res => {
        if (res.status === 0) {
          this.avList = res.info
        }
      })
      getUrlArray().then(res => {
        if (res.status === 0) {
          this.urlFilterList = res.info
        }
      })
      Promise.all([getWhiteList(), getBlacklist(), getBlacklistFile()]).then(res => {
        if (res[0].status === 0 && res[1].status === 0 && res[2].status === 0) {
          this.contentFilterList = res[0].info.concat(res[1].info).concat(res[2].info)
        }
      })
    },
    protoChange (data) {
      if (data === 'nothing') {
        this.record.sport = ''
      }
    }
  }
}
</script>
<style scoped lang="less">
.dialogContentBox {
  max-height: calc(100vh - 204px);
  overflow-y: auto;
}
</style>
